/*
Copyright 2020 The KubeSphere Authors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package controller

import (
	"fmt"
	"testing"
	"time"

	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/apimachinery/pkg/runtime"
	"k8s.io/client-go/tools/cache"
	"k8s.io/client-go/util/workqueue"
)

var (
	alwaysReady        = func() bool { return true }
	noResyncPeriodFunc = func() time.Duration { return 0 }
	controllerName     = "base-controler-test"
)

type fixture struct {
	t      *testing.T
	stopCh chan struct{}
	BaseController
	handleTimes int
}
type fakeObj struct {
	metav1.TypeMeta   `json:",inline"`
	metav1.ObjectMeta `json:"metadata,omitempty"`
}

func (in *fakeObj) DeepCopyInto(out *fakeObj) {
	*out = *in
	out.TypeMeta = in.TypeMeta
	in.ObjectMeta.DeepCopyInto(&out.ObjectMeta)
	return
}

// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new GlobalRole.
func (in *fakeObj) DeepCopy() *fakeObj {
	if in == nil {
		return nil
	}
	out := new(fakeObj)
	in.DeepCopyInto(out)
	return out
}

func (in *fakeObj) DeepCopyObject() runtime.Object {
	if c := in.DeepCopy(); c != nil {
		return c
	}
	return nil
}

func newFixture(t *testing.T, retryTimes int) *fixture {
	f := &fixture{}
	f.t = t
	f.stopCh = make(chan struct{})
	f.BaseController = BaseController{
		Workqueue: workqueue.NewNamedRateLimitingQueue(workqueue.DefaultControllerRateLimiter(), "Group"),
		Synced:    []cache.InformerSynced{alwaysReady},
		Name:      controllerName,
	}
	f.MaxRetries = retryTimes
	return f
}

func (f *fixture) reconcile(key string) error {
	f.handleTimes++
	f.t.Logf("Current key is %s", key)
	f.stopCh <- struct{}{}
	return nil
}

func (f *fixture) retryreconcile(key string) error {
	f.handleTimes++
	f.t.Logf("Current key is %s", key)
	if f.Workqueue.NumRequeues(key) == 2 {
		defer func(f *fixture) { f.stopCh <- struct{}{} }(f)
	}
	err := fmt.Errorf("retry times: %d", f.Workqueue.NumRequeues(key))
	return err
}

func createFakeobj() metav1.Object {

	var obj metav1.Object

	fake := fakeObj{
		ObjectMeta: metav1.ObjectMeta{Name: "Hello"},
		TypeMeta:   metav1.TypeMeta{},
	}
	obj = &fake
	return obj
}

func TestDequeue(t *testing.T) {
	f := newFixture(t, 0)
	f.Handler = f.reconcile

	go f.Run(1, f.stopCh)

	obj := createFakeobj()
	f.Enqueue(obj)

	<-f.stopCh

	if f.handleTimes != 1 {
		t.Error("Failed to call the handler!")
	}

}

func TestRetry(t *testing.T) {
	f := newFixture(t, 2)
	f.Handler = f.retryreconcile

	go f.Run(1, f.stopCh)

	obj := createFakeobj()
	f.Enqueue(obj)

	<-f.stopCh

	if f.handleTimes != f.MaxRetries+1 {
		t.Error("Failed to call the handler!")
	}

}
